package com.yyk.yiliao.ui.gongyong.activity;


import android.content.Intent;
import android.os.Bundle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.adapter.Detailllist_Gv_Adapter;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.bean.Shaixuan_Info;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.ui.activity.shopcart.ShopCart_Activity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.ui.login.activity.LogIn_Activity;
import com.yyk.yiliao.util.CheckDecimalPointUtil;
import com.yyk.yiliao.util.ebs.TwoStringEvent;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartAddcart;
import com.yyk.yiliao.bean.OrderCartCountkey_Info;
import com.yyk.yiliao.bean.StoreStoregoods_Info;
import com.yyk.yiliao.widget.diver.CustomDecoration;
import com.yyk.yiliao.widget.CustomGridView;
import com.yyk.yiliao.widget.paowuxian.BazierAnimView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 按症找药 -----商品列表
 */

public class DetailList_Activity extends BaseActivity {


    @BindView(R.id.nHome_search)
    TextView nHomeSearch;
    @BindView(R.id.mDetaillist_tab5_tv)
    TextView mDetaillistTab5Tv;
    @BindView(R.id.mDetaillist_tab5_iv)
    ImageView mDetaillistTab5Iv;
    @BindView(R.id.mDetaillist_tab5)
    LinearLayout mDetaillistTab5;
    @BindView(R.id.mDetaillist_rv)
    RecyclerView mDetaillistRv;
    @BindView(R.id.nav_view)
    LinearLayout navView;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;


    @BindView(R.id.tv_tab_1) //综合
            TextView tvTab1;
    @BindView(R.id.tv_tab_2) //销量
            TextView tvTab2;
    @BindView(R.id.tv_tab_3) //价格
            TextView tvTab3;
    @BindView(R.id.iv_tab_3_top)//价格箭头
            ImageView ivTab3Top;
    @BindView(R.id.iv_tab_3_bottom)
    ImageView ivTab3Bottom;


    //抛物线
    @BindView(R.id.cornerimg) //购物车图标
            ImageView cornerImg;
    @BindView(R.id.unread_msg_number)//购物车图标数量
            TextView msgNuber;
    @BindView(R.id.bezier_anim)
    BazierAnimView bazierAnimView;

    private List<String> mlist;
    private boolean mIsShrink = true;    //默认收缩
    //收缩时显示的行数
    private static final int SHOWED_LINES = 2;
    //GridView的列数
    private static final int NUM_COLUMNS = 3;
    private String cid;

    boolean flag = false; //价格高低判断

    final List<StoreStoregoods_Info.DataBean> data = new ArrayList<>();
    private BaseRecyclerAdapter<StoreStoregoods_Info.DataBean> adapter;

    public void initGetIntent() {
        initEventBus();

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void eventBusReceive(TwoStringEvent event) {
        cid = event.getMessage();
        String title = event.getTitle();
        setTitle(title);

    }

    private void initEventBus() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_detaillist;
    }

    @Override
    public void initView() {
        initToolbar();
    }

    private void initToolbar() {
        setBackArrow();
//        setTitle();
    }

    @Override
    public void initData() {
        initGetIntent();
        setView();
        initAdapter();
    }

    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<StoreStoregoods_Info.DataBean>(DetailList_Activity.this, data, R.layout.adapter_item_detaillist) {
            @Override
            public void convert(final BaseRecyclerHolder holder, final StoreStoregoods_Info.DataBean item, final int position, boolean isScrolling) {
                holder.setText(R.id.tv_name, item.getName());
                holder.setText(R.id.tv_describe, item.getDescribe());
                String money = CheckDecimalPointUtil.checkPoint(item.getMoney());
                holder.setText(R.id.tv_money, "¥" + money);
                holder.setText(R.id.tv_monthly, "月销" + item.getMonthly() + "件");
                holder.setText(R.id.tv_shopname, item.getShopname());
                holder.setImageByUrl(R.id.b_picture, ApiService.BASE_URL + item.getPic());
                int recipe = item.getRecipe();
                if (recipe == 0) {
                    //非处方
                    holder.getView(R.id.b_picturecfy).setVisibility(View.GONE);
                } else {
                    //处方
                    holder.getView(R.id.b_picturecfy).setVisibility(View.VISIBLE);
                }
                holder.getView(R.id.iv_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int uid = Hawk.get("uid", 0);
                        Logger.i("账号id==" + uid);
                        if (uid == 0) {
                            Intent intent2 = new Intent(DetailList_Activity.this, LogIn_Activity.class);
                            startActivity(intent2);
                        } else {
                            setBuyShop(item.getId(),holder.getView(R.id.iv_add),item.getPic());
                        }


                    }
                });
            }
        };
        mDetaillistRv.addItemDecoration(new CustomDecoration(DetailList_Activity.this, CustomDecoration.VERTICAL_LIST, R.drawable.divider_white_ef_1px, 0));
        mDetaillistRv.setLayoutManager(new LinearLayoutManager(DetailList_Activity.this, LinearLayoutManager.VERTICAL, false));
        mDetaillistRv.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
//                Intent intent = new Intent(DetailList_Activity.this, Detail_Activity.class);
//                EventBus.getDefault().postSticky(new MessageEvent(data.get(position).getId() + ""));
//                startActivity(intent);
                Bundle bundle = new Bundle();
                bundle.putInt("id", data.get(position).getId());

                startAct(Detail_Activity.class, bundle);

            }
        });

    }

    protected void setView() {
        initDrawlayout();
        //默认综合  1页
        Map<String, String> map = new TreeMap<>();
        map.put("page", 1 + "");//页数
        map.put("cid", cid);///自定义类
        map.put("type", 1 + ""); //默认综合

        map.put("sign", Md5Util2.createSign(map));
        initStoreGoodslist(map, true);

    }

    /**
     * 购物车数量
     */
    private void initShopNumber() {
        Map<String, String> map = new TreeMap<>();

        //        map.put("uid", 89 + "");
        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCarCountkey(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<OrderCartCountkey_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        ToastUtil.showShort(getActivity(), "商城异常");
                    }

                    @Override
                    public void onNext(OrderCartCountkey_Info info) {
                        Logger.w("购物车数量" + info.toString());
                        if (info.getCode() == 1) {
                            int dataNumber = info.getGoodstypes();
                            if (dataNumber == 0) {
                                msgNuber.setVisibility(View.INVISIBLE);
                            } else {
                                msgNuber.setText(dataNumber + "");
                                msgNuber.setVisibility(View.VISIBLE);

                            }

                        }
                    }
                });

    }

    private void initStoreGoodslist(Map<String, String> map, final boolean flag) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postStoreGoods(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<StoreStoregoods_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(StoreStoregoods_Info info) {
                        Logger.i("商品列表:" + info.toString());
                        if (info.getCode() == 1) {

                            if (info instanceof StoreStoregoods_Info) {
                                if (flag) {
                                    data.clear();
                                }
                                if (info.getData() != null && info.getData().size() > 0) {
                                    mDetaillistRv.setVisibility(View.VISIBLE);

                                    data.addAll(info.getData());
                                } else {
                                    mDetaillistRv.setVisibility(View.GONE);
                                }
                                adapter.notifyDataSetChanged();
                            }
                        } else {
//                            mView.onFailure("失败");//失败
                        }
                    }


                });

    }

    @Override
    public void onResume() {
        super.onResume();
        //刷新购物车数量
        initShopNumber();
    }

    /**
     * 刷新购物车数量
     */
    public void reshefeshShopNumber(final ImageView buy, final String pic) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bazierAnimView.startCartAnim(buy, cornerImg, R.layout.l_move, pic);
                initShopNumber();
            }
        });

    }

    /**
     * 添加购物车
     *
     * @param id
     */
    private void setBuyShop(int id, final View view, final String pic) {
        Map<String, String> map = new TreeMap<>();

        map.put("uid", Hawk.get("uid", 0) + "");
//                map.put("uid", 89 + "");
        map.put("gid", id + "");
        map.put("num", "1");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartAddcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartAddcart>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(CartAddcart info) {
                        Logger.e("商品详情加入购物车" + info.getCode());
                        if (info.getCode() == 1) {
                            reshefeshShopNumber((ImageView) view, pic);
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(DetailList_Activity.this, "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(DetailList_Activity.this, "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(DetailList_Activity.this, "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(DetailList_Activity.this, "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(DetailList_Activity.this, "商品删除失败 ");
                        }
                    }
                });
    }

    private void initDrawlayout() {
        View view = LayoutInflater.from(this).inflate(R.layout.activity_drawlayout_right, null);
        navView.addView(view);
        RecyclerView nRv = view.findViewById(R.id.nRv);
        Button btn_confirm = view.findViewById(R.id.btn_confirm);
        nRv.setLayoutManager(new LinearLayoutManager(this));
        //模拟数据
        List<String> string = new ArrayList<>();
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        string.add("白云山");
        List<String> string2 = new ArrayList<>();
        string2.add("穿山甲");
        string2.add("穿山甲");
        string2.add("穿山甲");
        string2.add("穿山甲");
        string2.add("穿山甲");
        List<String> string3 = new ArrayList<>();
        string3.add("盒装");
        string3.add("袋装");

        Shaixuan_Info info = new Shaixuan_Info("品牌", 0, string);
        Shaixuan_Info info2 = new Shaixuan_Info("折扣", 0, string2);
        Shaixuan_Info info3 = new Shaixuan_Info("包装", 0, string3);

        List<Shaixuan_Info> list = new ArrayList<>();
        list.add(info);
        list.add(info2);
        list.add(info3);

        final BaseRecyclerAdapter<Shaixuan_Info> adapter = new BaseRecyclerAdapter<Shaixuan_Info>(DetailList_Activity.this, list, R.layout.activity_detail_shaixuan) {


            @Override
            public void convert(BaseRecyclerHolder holder, Shaixuan_Info item, int position, boolean isScrolling) {
                holder.setText(R.id.tv, item.getTitle());

                //Gridview
                TextView tv2 = holder.getView(R.id.tv2);

                final CustomGridView b_grade = holder.getView(R.id.b_grade);
                //默认这么多
                final List<String> mList = item.getList();
                final List<String> mList2 = new ArrayList<>();
                if (mList.size() > 6) {
                    for (int i = 0; i < NUM_COLUMNS * SHOWED_LINES; i++) {
                        mList2.add(mList.get(i));
                    }
                    tv2.setVisibility(View.VISIBLE);
                } else {
                    for (int i = 0; i < mList.size(); i++) {
                        mList2.add(mList.get(i));
                    }
                    tv2.setVisibility(View.GONE);
                }
                mlist = mList2;
                final Detailllist_Gv_Adapter adapter = new Detailllist_Gv_Adapter(getApplicationContext(), mlist);
                //隐藏更多
                tv2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //展开
                        if (mIsShrink) {
                            mlist = mList;
                            mIsShrink = false;
                            adapter.setData(mlist);
                        }
                        //收缩
                        else {
                            mlist = mList2;
                            mIsShrink = true;
                            adapter.setData(mlist);
                        }

                        setListViewHeightBasedOnChildren(b_grade);
                    }
                });
                setListViewHeightBasedOnChildren(b_grade);
                b_grade.setAdapter(adapter);
                Logger.e("gengduo" + mList.size());


            }
        };
        nRv.setAdapter(adapter);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.closeDrawer(navView);
            }
        });
    }


    /**
     * 当GridView外层有ScrollView时，需要动态设置GridView高度
     *
     * @param gridview
     */
    protected void setListViewHeightBasedOnChildren(GridView gridview) {
        if (gridview == null)
            return;
        ListAdapter listAdapter = gridview.getAdapter();
        if (listAdapter == null)
            return;

        int totalHeight;
        //向上取整
        int count = (int) Math.ceil(listAdapter.getCount() / 4.0);
        //获取一个子view
        View itemView = listAdapter.getView(0, null, gridview);
        //测量View的大小
        itemView.measure(0, 0);
        totalHeight = itemView.getMeasuredHeight();
        ViewGroup.LayoutParams params = gridview.getLayoutParams();
        //设置GridView的布局高度
        params.height = totalHeight * count;
        gridview.setLayoutParams(params);
    }

    /**
     * 1.综合
     * 2.销量
     * 3.价格
     *
     * @param view
     */
    @OnClick({R.id.tv_tab_1, R.id.tv_tab_2, R.id.ll_tab_3, R.id.nHome_search, R.id.mDetaillist_tab5, R.id.cornerimg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tab_1:
                hideJiantouColor();
                tvTab1.setTextColor(getResources().getColor(R.color.blue_14));
                flag = false;

                Map<String, String> map = new TreeMap<>();
                map.put("cid", cid);///自定义类
                map.put("page", 1 + "");//页数
                map.put("type", 1 + ""); //默认综合
                map.put("sign", Md5Util2.createSign(map));
                initStoreGoodslist(map, true);
                break;
            case R.id.tv_tab_2:
                hideJiantouColor();
                tvTab2.setTextColor(getResources().getColor(R.color.blue_14));
                flag = false;
                Map<String, String> map2 = new TreeMap<>();
                map2.put("cid", cid);//cid
                map2.put("page", 1 + "");//页数
                map2.put("type", 2 + ""); //类型
                map2.put("sign", Md5Util2.createSign(map2));
                initStoreGoodslist(map2, true);
                break;
            case R.id.ll_tab_3:
                hideJiantouColor();
                tvTab3.setTextColor(getResources().getColor(R.color.blue_14));
                Map<String, String> map3 = new TreeMap<>();
                map3.put("cid", cid);//cid
                map3.put("page", 1 + "");//页数
                map3.put("type", 3 + ""); //类型
                if (flag) {
                    map3.put("order", 1 + ""); //价格低高
                    ivTab3Top.setImageResource(R.mipmap.icon_solb_shang);
                    ivTab3Bottom.setImageResource(R.mipmap.icon_solb_xiax);
                    flag = false;
                } else {
                    map3.put("order", 2 + ""); //价格高低
                    ivTab3Top.setImageResource(R.mipmap.icon_solb_shangx);
                    ivTab3Bottom.setImageResource(R.mipmap.icon_solb_xia
                    );
                    flag = true;
                }
                map3.put("sign", Md5Util2.createSign(map3));

                initStoreGoodslist(map3, true);
                break;
            case R.id.cornerimg:
                startAct(ShopCart_Activity.class);
                break;
            case R.id.nHome_search:
                break;
            case R.id.mDetaillist_tab5:
                ToastUtil.showShort(DetailList_Activity.this, "5");

                if (drawerLayout.isDrawerOpen(navView)) {
                    drawerLayout.closeDrawer(navView);
                } else {
                    drawerLayout.openDrawer(navView);
                }
                break;
        }
    }

    /**
     * 清除价格上下箭头  和文字颜色
     */
    private void hideJiantouColor() {
        tvTab1.setTextColor(getResources().getColor(R.color.black_20));
        tvTab2.setTextColor(getResources().getColor(R.color.black_20));
        tvTab3.setTextColor(getResources().getColor(R.color.black_20));

        ivTab3Top.setImageResource(R.mipmap.icon_solb_shang);
        ivTab3Bottom.setImageResource(R.mipmap.icon_solb_xia);
    }


}
